#!/usr/bin/env python3
"""
Example script demonstrating R3(phi) rotation matrix usage
This script shows how to properly import and use the R3 function from casestab
"""

import sys
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')  # Use non-interactive backend
import matplotlib.pyplot as plt

# Add the current directory to Python path to import the module
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from casestab import math_functions as mf

def main():
    print("=== R3(phi) Rotation Matrix Examples ===\n")
    
    # Example 1: Basic R3(phi) usage
    print("1. Basic R3(phi) usage:")
    phi = np.pi/4  # 45 degrees
    R = mf.R3(phi)
    print(f"R3(π/4) = ")
    print(R)
    print()
    
    # Example 2: Rotating a vector
    print("2. Rotating a vector:")
    v = np.array([1.0, 0.0, 0.0])  # Unit vector along x-axis
    v_rotated = R @ v
    print(f"Original vector: {v}")
    print(f"Rotated by π/4: {v_rotated}")
    print()
    
    # Example 3: Multiple rotation angles
    print("3. Multiple rotation angles:")
    angles = [0, np.pi/6, np.pi/4, np.pi/3, np.pi/2]  # 0, 30, 45, 60, 90 degrees
    vectors = []
    
    for angle in angles:
        R_angle = mf.R3(angle)
        v_rot = R_angle @ np.array([1.0, 0.0, 0.0])
        vectors.append(v_rot)
        print(f"Angle {np.degrees(angle):3.0f}°: [{v_rot[0]:6.3f}, {v_rot[1]:6.3f}, {v_rot[2]:6.3f}]")
    print()
    
    # Example 4: Visualization
    print("4. Creating visualization...")
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
    
    # Plot 1: Vector rotation in x-y plane
    angles_plot = np.linspace(0, 2*np.pi, 100)
    x_coords = []
    y_coords = []
    
    for angle in angles_plot:
        R_plot = mf.R3(angle)
        v_plot = R_plot @ np.array([1.0, 0.0, 0.0])
        x_coords.append(v_plot[0])
        y_coords.append(v_plot[1])
    
    ax1.plot(x_coords, y_coords, 'b-', linewidth=2, label='Unit circle')
    ax1.plot([0, 1], [0, 0], 'r-', linewidth=3, label='Original vector')
    
    # Mark specific angles
    for i, angle in enumerate(angles):
        R_mark = mf.R3(angle)
        v_mark = R_mark @ np.array([1.0, 0.0, 0.0])
        ax1.plot([0, v_mark[0]], [0, v_mark[1]], 'g-', alpha=0.7)
        ax1.plot(v_mark[0], v_mark[1], 'go', markersize=8)
        ax1.text(v_mark[0]*1.1, v_mark[1]*1.1, f'{np.degrees(angle):.0f}°', 
                fontsize=10, ha='center')
    
    ax1.set_xlim(-1.2, 1.2)
    ax1.set_ylim(-1.2, 1.2)
    ax1.set_xlabel('X coordinate')
    ax1.set_ylabel('Y coordinate')
    ax1.set_title('R3(φ) Vector Rotation in X-Y Plane')
    ax1.grid(True, alpha=0.3)
    ax1.legend()
    ax1.set_aspect('equal')
    
    # Plot 2: Rotation matrix elements
    angles_matrix = np.linspace(0, 2*np.pi, 200)
    cos_vals = np.cos(angles_matrix)
    sin_vals = np.sin(angles_matrix)
    
    ax2.plot(np.degrees(angles_matrix), cos_vals, 'b-', label='cos(φ)', linewidth=2)
    ax2.plot(np.degrees(angles_matrix), sin_vals, 'r-', label='sin(φ)', linewidth=2)
    ax2.plot(np.degrees(angles_matrix), -sin_vals, 'g-', label='-sin(φ)', linewidth=2)
    
    ax2.set_xlabel('Angle φ [degrees]')
    ax2.set_ylabel('Value')
    ax2.set_title('R3(φ) Matrix Elements')
    ax2.grid(True, alpha=0.3)
    ax2.legend()
    ax2.set_xlim(0, 360)
    
    plt.tight_layout()
    plt.savefig('r3_rotation_examples.png', dpi=300, bbox_inches='tight')
    print("Visualization saved as 'r3_rotation_examples.png'")
    print()
    
    # Example 5: Wind turbine context
    print("5. Wind turbine context example:")
    blade_angle = 0.1  # 0.1 radians ≈ 5.7 degrees
    R_blade = mf.R3(blade_angle)
    
    # Simulate blade section coordinates
    local_coords = np.array([
        [0.0, 1.0, 0.0],  # Leading edge
        [0.0, -1.0, 0.0], # Trailing edge
        [0.0, 0.0, 0.0]   # Center
    ])
    
    print(f"Blade rotation angle: {np.degrees(blade_angle):.1f}°")
    print("Local coordinates -> Global coordinates:")
    for i, coord in enumerate(local_coords):
        global_coord = R_blade @ coord
        print(f"  Point {i+1}: [{coord[0]:4.1f}, {coord[1]:4.1f}, {coord[2]:4.1f}] -> "
              f"[{global_coord[0]:6.3f}, {global_coord[1]:6.3f}, {global_coord[2]:6.3f}]")
    
    print("\n=== Examples completed successfully! ===")

if __name__ == "__main__":
    main()
